package zdream.pmfield.stage.message;

import java.util.function.Function;

import zdream.pmfield.core.Result;

/**
 * @author Zdream
 * @date 2023-11-13
 * @since 0.0.1
 */
public abstract class NeedReplyMessage<R extends StageReply> extends StageMessage {
	public transient Function<ActionRequestReply, Result> validator;
	private boolean replyReceived;

	public abstract R createReplyTemplate();

	/**
	 * 线程不安全, 请自行保证下个 commit 在上个 commit 调用完再调用
	 */
	public Result commit(ActionRequestReply reply) {
		if (replyReceived) {
			return Result.ofFailure("你已经提交成功过了");
		}
		final Result result = validator.apply(reply);
		if (result.success) {
			replyReceived = true;
		}
		return result;
	}

	public boolean isReplyReceived() {
		return replyReceived;
	}

	@Override
	public boolean needReply() {
		return true;
	}

	@Override
	public NeedReplyMessage<?> caseToNeedReplyMessage() {
		return this;
	}
}
